package com.coderli.onecoder.agent.task;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.coderli.onecoder.shared.model.CommandRequest;
import com.coderli.onecoder.shared.model.TaskResult;

/**
 * 默认的Agent任务执行线程池
 * 
 * @author lihzh
 * @date 2012-7-4 下午3:41:17
 */
public class SimpleCommandPool implements CommandExecutorPool {
	
	private static final Logger log = LoggerFactory.getLogger(SimpleCommandPool.class);

	private ExecutorService executorService;

	@Override
	public void init() {
		/*
		 * 采用cachedPool的默认配置。 最少线程(core)：0 最大线程：Integer.MAX_VALUE 空闲线程等待时间：60秒
		 */
		executorService = Executors.newCachedThreadPool();

	}

	@Override
	public TaskResult runTask(CommandRequest request) {
		Future<TaskResult> future = executorService.submit(new SimpleTaskRunner(request));
		try {
			future.isDone();
			TaskResult result = future.get();
			log.info("Handle finish.");
			return result;
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static class SimpleTaskRunner implements Callable<TaskResult> {
		
		@SuppressWarnings("unused")
		private CommandRequest request;
		
		private SimpleTaskRunner(CommandRequest request) {
			this.request = request;
		}

		@Override
		public TaskResult call() throws Exception {
			TaskResult result = new TaskResult();
			return result;
		}
		
	}

}
